import { defineStore } from "pinia";

import { computed, ref } from "vue";
import { useUserStore } from "./userStore";

import { findNewCartListAPI, insertCartAPI, delCartAPI } from "@/apis/cart";

export const useCartStore = defineStore(
  "cart",
  () => {
    const userStore = useUserStore();

    const isLogin = computed(() => userStore.userInfo.token);

    // 1.定义state-cartList
    const cartList = ref([]);

    //获取最新购物车列表action
    const updateNewList = async () => {
      const res = await findNewCartListAPI();
      cartList.value = res.result;
    };

    //   2.定义action - addCatt--添加购物车
    const addCart = async (goods) => {
      const { skuId, count } = goods;
      // 判断登录与非登录逻辑
      if (isLogin.value) {
        // 登录后的加入购物车逻辑
        await insertCartAPI({ skuId, count });
        updateNewList();
      } else {
        // 添加购物城逻辑
        // 已添加过 - count +1
        // 未添加过 - 直接 push
        // 思路：通过匹配传递过来的商品对象中的skuId能不能再cartList找到 找到就添加过
        const item = cartList.value.find((item) => goods.skuId === item.skuId);
        if (item) {
          // 找到了
          item.count++;
        } else {
          cartList.value.push(goods);
        }
      }
    };

    // 删除购物车
    const delCart = async (skuId) => {
      if (isLogin) {
        // 调用接口实现删除
        await delCartAPI([skuId]);
        updateNewList();
      } else {
        // 1.找到要删除项的下标值 --splice
        // 2.使用数组的过滤方法 - filter
        const idx = cartList.value.findIndex((item) => skuId === item.skuId);
        cartList.value.splice(idx, 1);
      }
    };

    // 清除购物车
    const clearCart = () => {
      cartList.value = [];
    };

    // 单选功能

    const singleCheck = (skuId, selected) => {
      // 通过skuID找到要修改的 将其 selected改为要修改的
      const item = cartList.value.find((item) => item.skuId === skuId);
      item.selected = selected;
    };

    // 计算属性
    // 1.总的数量  count和
    // 2.总价  count*price

    const allCount = computed(() =>
      cartList.value.reduce((a, c) => a + c.count, 0)
    );
    const allPrice = computed(() =>
      cartList.value.reduce((a, c) => a + c.count * c.price, 0)
    );

    // 是否全选
    const isAll = computed(() => cartList.value.every((item) => item.selected));

    // 全选功能
    const allCheck = (selected) => {
      // 把selected中每一项设置为true
      cartList.value.forEach((item) => (item.selected = selected));
    };

    // 已选则数量
    const selectedCount = computed(() =>
      cartList.value
        .filter((item) => item.selected)
        .reduce((a, c) => a + c.count, 0)
    );

    // 已选择商品合计
    const selectedPrice = computed(() =>
      cartList.value
        .filter((item) => item.selected)
        .reduce((a, c) => a + c.count * c.price, 0)
    );

    return {
      cartList,
      addCart,
      delCart,
      allCount,
      allPrice,
      singleCheck,
      isAll,
      allCheck,
      selectedPrice,
      selectedCount,
      clearCart,
      updateNewList,
    };
  },
  { persist: true }
);
